import 'dart:convert';

Map<String, String> classReplace = {
  // "PartElement": "Chapter"
};

List<String?> classList = [];
String replace(String content) {
  classList = [];
  var res = content;
  res = res.replaceAllMapped(
    RegExp(r'from\(json\["(\w+)"\]\.map'),
    (match) => 'from((json["${match.group(1)}"] ?? []).map',
  );

  List<String> lines = LineSplitter.split(res).toList();
  lines.removeRange(0, 10);
  lines.insert(
      0, "import 'package:helixlife_app_basis/helixlife_app_basis.dart';");
  res = lines.join('\n');

  // res = res.replaceAll('String ', 'String? ');
  // res = res.replaceAll('int ', 'int? ');
  // res = res.replaceAll('bool ', 'bool? ');
  // res = res.replaceAll('double ', 'double? ');

  res = res.replaceAllMapped(
    RegExp(r'List<(\w+)>\s+(\w+)\s*;'),
    (match) => 'List<${match.group(1)}>? ${match.group(2)};',
  );

  // res = res.replaceAll('.map((x)', '??[].map((x)');
  res = res.replaceAllMapped(
    RegExp(r'List<dynamic>\.from\((\w+)\.map'),
    (match) => 'List<dynamic>.from((${match.group(1)} ?? []).map',
  );
  res = res.replaceAllMapped(
      RegExp(r'(\w+):\s*(\w+)\.fromJson\(json\["(\w+)"]\)'), (match) {
    return '${match.group(1)}: json["${match.group(3)}"] == null ? null :  ${match.group(2)}.fromJson(json["${match.group(3)}"])';
  });

  res = res.replaceAllMapped(
    RegExp(r'Map<(\w+),\s(\w+)>\s(\w+);'),
    (match) => 'Map<${match.group(1)}, ${match.group(2)}>? ${match.group(3)};',
  );
  res = res.replaceAllMapped(
    RegExp(r'\s(\w+)\s(\w+);'),
    (match) => '${match.group(1)}? ${match.group(2)};',
  );
  res = res.replaceAllMapped(
    RegExp(
        r'Map\.from\((\w+)\)\.map\(\(k, v\) => MapEntry<String, dynamic>\(k, v\)\),'),
    (match) =>
        '${match.group(1)} != null ? Map.from(${match.group(1)}!).map((k, v) => MapEntry<String, dynamic>(k, v)):null,',
  );

  res = _classSetting(res);

  classReplace.forEach((key, value) {
    res = res.replaceAll(key, value);
  });

  for (var element in classList) {
    if (element != null) {
      res = res.replaceAll(element, "${element}Bean");
    }
  }

  return res;
}

String _classSetting(String content) {
  String code = content;
  String newCode = code.replaceAllMapped(
    RegExp(r'class\s(\w+)\s*{'),
    (match) {
      print(match.group(1));
      classList.add(match.group(1));
      return 'class ${match.group(1)} implements JsonBean<${match.group(1)}>{\n@override\n${match.group(1)}? fromJson(Map<String, dynamic>? json) {\nif (json == null) {return null;}\nreturn ${match.group(1)}.fromJson(json);\n}';
    },
  );

  newCode = newCode.replaceAll('Map<String, dynamic> toJson() => {',
      '@override\nMap<String, dynamic> toJson() => {');
  return newCode;
}
